package com.jiuyou.storeController.product;

import com.alibaba.fastjson.JSONObject;
import com.jiuyou.storeController.common.StoreBaseController;
import com.ruoyi.adapaySettleaccount.domain.AdapaySettleaccount;
import com.ruoyi.adapaySettleaccount.service.IAdapaySettleaccountService;
import com.ruoyi.common.constant.DicConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.order.domain.StoreProductOrder;
import com.ruoyi.order.service.IStoreProductOrderService;
import com.ruoyi.product.domain.StoreProduct;
import com.ruoyi.product.domain.StoreProductBack;
import com.ruoyi.product.domain.StoreProductJoint;
import com.ruoyi.product.service.IStoreProductBackService;
import com.ruoyi.product.service.IStoreProductJointService;
import com.ruoyi.product.service.IStoreProductService;
import com.ruoyi.richEditor.domain.RichEditorAttachment;
import com.ruoyi.richEditor.service.IRichEditorAttachmentService;
import com.ruoyi.store.domain.Store;
import com.ruoyi.common.core.domain.entity.StoreUserRole;
import com.ruoyi.store.service.IStoreService;
import com.ruoyi.storeclassify.domain.Storeclassify;
import com.ruoyi.storeclassify.service.IStoreclassifyService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author chengliang
 * @date 2021/11/22
 **/
@RestController
@RequestMapping("/store/storeProduct")
@Api(tags = {"团单控制器"})
public class StoreProductStoreController extends StoreBaseController {

    @Autowired
    private IStoreProductService productService;
    @Autowired
    private IStoreProductBackService backService;
    @Autowired
    private IRichEditorAttachmentService editorService;
    @Autowired
    private IStoreService storeService;
    @Autowired
    private IStoreclassifyService classifyService;
    @Autowired
    private IRichEditorAttachmentService richEditorService;
    @Autowired
    private IAdapaySettleaccountService adapaySettleaccountService;
    @Autowired
    private IStoreProductJointService productServiceJoint;
    @Autowired
    private IStoreProductOrderService storeProductOrderService;

    @PutMapping
    @ApiOperation("插入")
    public StoreProduct save(@ApiParam @RequestBody StoreProduct product){
        StoreUserRole role = getStoreUserRole();
        if(role == null){
            throw new CustomException("暂无数据");
        }
        RichEditorAttachment richEditorAttachment = editorService.selectRichEditorAttachmentById(product.getInfoId());
        Store store = storeService.selectStoreById(role.getStoreId());
        Storeclassify storeclassify = classifyService.selectStoreclassifyById(product.getClassifyId());
        product.setService(store.getServiceItem());
        product.setClassifyParentId(storeclassify.getParentId());
        product.setStoreId(store.getId());
        product.setStoreName(store.getStoreName());
        product.setProvinceName(store.getProvinceName());
        product.setProvinceCode(store.getProvinceCode());
        product.setCityName(store.getCityName());
        product.setCityCode(store.getCityCode());
        product.setLatitude(store.getLatitude());
        product.setLongitude(store.getLongitude());
        product.setGeoCode(store.getGeoCode());
        product.setSalesNum(0L);
        product.setCreateBy(getLoginStoreUserId());
        product.setAdCode(store.getAdCode());
        product.setAdName(store.getAdName());
        product.setCreateType(DicConstants.BUSINESS_Business.getCode());
        product.setState(DicConstants.SYS_N.getCode());
        StoreProductBack back = new StoreProductBack(product,richEditorAttachment.getAttValue());
        back.setCreateBy(getLoginStoreUserId());
        back.setCreateType(DicConstants.BUSINESS_Business.getCode());
        backService.insertStoreProductBack(back);
        product.setProductBackId(back.getId());
        productService.insertStoreProduct(product);
        back.setProductId(product.getId());
        backService.updateStoreProductBack(back);
        return product;
    }
    private void updateSecondClassify(Store store){

        StoreProduct productParam = new StoreProduct();
        productParam.setStoreId(store.getId());
        productParam.setState(DicConstants.SYS_Y.getCode());
        List<Storeclassify> classifyList= classifyService.selectStoreclassifyList(new Storeclassify());
        Map<Long,String> classifyMap=classifyList.stream().collect(Collectors.toMap(Storeclassify::getId,Storeclassify::getClassifyName));
        List<StoreProduct> products = productService.selectStoreProductList(productParam);
        products.stream().distinct().collect(Collectors.toList());
        StringBuilder builder= new StringBuilder(",");
        List<Long> ids = new ArrayList<>();
        List<String> names = new ArrayList<>();
        products.forEach(e->{
            ids.add(e.getClassifyId());
            names.add(classifyMap.get(e.getClassifyId())+e.getProductName());
        });
        List<Long> collect = ids.stream().distinct().collect(Collectors.toList());
        List<String> collect1 = names.stream().distinct().collect(Collectors.toList());
        collect.forEach(e->{
            builder.append(e.toString()).append(",");
        });
        StringBuilder builder1= new StringBuilder(",");
        collect1.forEach(e->{
            builder1.append(e).append(",");
        });
        store.setProductNames(builder1.toString());
        store.setSecondClassify(builder.toString());

        storeService.updateStore(store);
    }


    /**
     * 商品详情
     * */
    @GetMapping("/getInfo/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        StoreProduct storeProduct=productService.selectStoreProductById(id);
        if(null==storeProduct){
            return AjaxResult.error("参数错误");
        }
        JSONObject jso=new JSONObject();
        jso.put("storeId",storeProduct.getStoreId());
        jso.put("storeName",storeProduct.getStoreName());
        jso.put("productName",storeProduct.getProductName());
        jso.put("productImage",storeProduct.getProductImage());
        jso.put("itemDetail",storeProduct.getItemDetail());
        jso.put("infoId",storeProduct.getInfoId());
        jso.put("price",storeProduct.getPrice());
        jso.put("salesNum",storeProduct.getSalesNumShow());
        jso.put("state",storeProduct.getState());
        jso.put("fixedTimeState",storeProduct.getFixedTimeState());
        jso.put("useStartTime", DateUtils.dateTime(storeProduct.getUseStartTime()));
        jso.put("useEndTime", DateUtils.dateTime(storeProduct.getUseEndTime()));
        jso.put("disabledDate",storeProduct.getDisabledDate());
        jso.put("validDay",storeProduct.getValidDay());
        jso.put("appoinNum",storeProduct.getAppoinNum());
        jso.put("appoinUnit",storeProduct.getAppoinUnit());
        jso.put("peopleRight",storeProduct.getPeopleRight());
        jso.put("peopleNum",storeProduct.getPeopleNum());
        jso.put("ruleReminder",storeProduct.getRuleReminder());
        jso.put("reminder",storeProduct.getReminder());
        jso.put("service",storeProduct.getService());
        jso.put("couponsMaxNewUse",storeProduct.getCouponsMaxNewUse());
        jso.put("couponsMaxAll",storeProduct.getCouponsMaxAll());
        jso.put("storePrice",storeProduct.getStorePrice());
        jso.put("backId",storeProduct.getProductBackId());
        jso.put("classifyId",storeProduct.getClassifyId());

        return AjaxResult.success(jso);
    }

    @ApiOperation("获取单个团单")
    @GetMapping("/{id}")
    public JSONObject get(@PathVariable Long id ){
        JSONObject jsonObject = returnFail();
        StoreProduct product = productService.selectStoreProductById(id);
        jsonObject.put("product",product);
        returnSuccess(jsonObject);
        return jsonObject;
    }
    @ApiOperation("获取团单列表")
    @GetMapping("/list")
    public TableDataInfo list(String state){
        StoreUserRole role = getStoreUserRole();
        if(role == null){
            return getDataTable(new ArrayList<>());
        }
        System.out.println("tangyin666");
        System.out.println(role.getStoreId());
        StoreProduct storeProduct = new StoreProduct();
//        storeProduct.setStoreId(role.getStoreId());
//        if(!"all".equals(state))
            //storeProduct.setState(state);
        startPage();

        if(state.equals("Y")){
            storeProduct.setStoreId(role.getStoreId());
            List<StoreProduct> storeProductList = productService.selectStoreProductListByY(storeProduct);
            getForList(storeProductList,role.getStoreId());
            return getDataTable(storeProductList);
        }else if(state.equals("N")){
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("storeId", role.getStoreId());
            List<StoreProductJoint> psjList = productServiceJoint.selectStoreProductJointByParamTrue(params);

            Long[] ids= new Long[psjList.size()];
            Integer i = 0;
            for (StoreProductJoint storeProductJointOne: psjList ) {
                //ids = addElement(ids, storeProductJointOne.getStoreProductId());
                ids[i] = storeProductJointOne.getStoreProductId();
                i++;
            }
            System.out.println("tangddd");
            System.out.println(psjList);
            System.out.println(ids);

            // 打印数组中的元素
            for (Long element : ids) {
                System.out.println(element);
            }

            storeProduct.setStoreId(role.getStoreId());
//            List<StoreProduct> storeProductList = productService.selectStoreProductListByN(storeProduct);
            List<StoreProduct> storeProductList = productService.selectStoreProductListByIds(ids,role.getStoreId());

            getForList(storeProductList,role.getStoreId());
            return getDataTable(storeProductList);
        }else{
            List<StoreProduct> storeProductList = productService.selectStoreProductList(storeProduct);
            getForList(storeProductList,role.getStoreId());
            return getDataTable(storeProductList);
        }
    }

    public void getForList(List<StoreProduct> storeProductList,Long storeId){
        for (StoreProduct storeProductone : storeProductList) {
            System.out.println(storeProductone.getId());
            StoreProductJoint  StoreProductJointOne = productServiceJoint.selectStoreProductByStoreIdAndStoreId(storeId,storeProductone.getId());
            System.out.println("ddd");
            System.out.println(StoreProductJointOne);
            if(StoreProductJointOne == null){
                storeProductone.setState(DicConstants.SYS_N.getCode());
                storeProductone.setStoreProductJointId(0L);
                storeProductone.setStoreId(0L);
            }else{
                System.out.println("tang098");
                System.out.println(StoreProductJointOne.getState());
                Long storeIdn = StoreProductJointOne.getStoreId();

                //实际到账（查询订单付款了的）
                StoreProductOrder storeProductOrder = new StoreProductOrder();
                storeProductOrder.setStoreId(storeIdn);
                storeProductOrder.setProductId(storeProductone.getId());
                storeProductOrder.setPayState("Y");
                List<StoreProductOrder> spoList = storeProductOrderService.selectStoreProductOrderList(storeProductOrder);

                storeProductone.setState(StoreProductJointOne.getState());
                storeProductone.setStoreProductJointId(StoreProductJointOne.getId());
                storeProductone.setStoreId(storeIdn);
            }
        }
    }

    public static Long[] addElement(Long[] array, Long newValue) {
        // 创建一个新的数组，长度比原来的数组大1
        Long[] newArray = new Long[array.length + 1];

        // 将原来数组中的元素复制到新数组中
        System.arraycopy(array, 0, newArray, 0, array.length);

        // 将新元素添加到新数组的最后一个位置
        newArray[array.length] = newValue;

        // 更新原来的数组
        return newArray;
    }


    @PutMapping("/edit")
    @ApiOperation("修改")
    public StoreProduct edit(@ApiParam @RequestBody StoreProduct product){
        StoreUserRole storeUserRole = getStoreUserRole();
        Store store = storeService.selectStoreById(storeUserRole.getStoreId());
        RichEditorAttachment richEditorAttachment = editorService.selectRichEditorAttachmentById(product.getInfoId());
        product.setCreateType(DicConstants.BUSINESS_Business.getCode());
        product.setState(DicConstants.SYS_N.getCode());
        StoreProductBack back = new StoreProductBack(product,richEditorAttachment.getAttValue());
        back.setCreateBy(getLoginStoreUserId());
        back.setCreateType(DicConstants.BUSINESS_Business.getCode());
        backService.insertStoreProductBack(back);
        product.setProductBackId(back.getId());
        productService.updateStoreProduct(product);
        return product;
    }

    /**
     * 新的上架
     * */
    @PostMapping("/shelvesnew/up/{productId}")
    public JSONObject shelvesUpnew(@PathVariable Long productId){
        JSONObject json = new JSONObject();
        json.put("success",false);
        json.put("msg","上架失败");
        StoreUserRole role = getStoreUserRole();
        if(role == null){
            return json;
        }
        StoreProduct  storeProduct = productService.selectStoreProductById(productId);
        if(storeProduct == null){
            json.put("msg","没有这个商品");
            return json;
        }
        Store store = storeService.selectStoreById(role.getStoreId());
        Long storeId = role.getStoreId();
        StoreProductJoint storeProductJointOne = productServiceJoint.selectStoreProductByStoreIdAndStoreId(storeId,productId);
        StoreProductJoint storeproductJoint = new StoreProductJoint();

        storeproductJoint.setStoreId(store.getId());
        storeproductJoint.setStoreProductId(productId);
        storeproductJoint.setStoreUserId(getLoginStoreUserId());
        storeproductJoint.setState(DicConstants.SYS_Y.getCode());
        storeproductJoint.setUpTime(new Date());
        storeproductJoint.setUpUser(getLoginStoreUserId());

        if(storeProductJointOne == null){
            //添加
            productServiceJoint.insertStoreProductJoint(storeproductJoint);
        }else{
            //修改
            storeproductJoint.setId(storeProductJointOne.getId());
            productServiceJoint.updateStoreProductJoint(storeproductJoint);
        }

        json.put("success",true);
        json.put("msg","上架成功");
        return json;
    }

    /**
     * 新的下架
     * */
    @PostMapping("/shelvesnew/down/{productId}")
    public JSONObject shelvesDownnew(@PathVariable Long productId){
        JSONObject json = new JSONObject();
        json.put("success",false);
        json.put("msg","下架失败");
        StoreUserRole role = getStoreUserRole();
        if(role == null){
            return json;
        }
        StoreProduct  storeProduct = productService.selectStoreProductById(productId);
        if(storeProduct == null){
            json.put("msg","没有这个商品");
            return json;
        }
        Store store = storeService.selectStoreById(role.getStoreId());
        Long storeId = role.getStoreId();
        StoreProductJoint storeProductJointOne = productServiceJoint.selectStoreProductByStoreIdAndStoreId(storeId,productId);
        StoreProductJoint storeproductJoint = new StoreProductJoint();

        storeproductJoint.setStoreId(store.getId());
        storeproductJoint.setStoreProductId(productId);
        storeproductJoint.setStoreUserId(getLoginStoreUserId());
        storeproductJoint.setState(DicConstants.SYS_N.getCode());
        storeproductJoint.setOffTime(new Date());
        storeproductJoint.setOffUser(getLoginStoreUserId());

        if(storeProductJointOne == null){
            //添加
            productServiceJoint.insertStoreProductJoint(storeproductJoint);
        }else{
            //修改
            storeproductJoint.setId(storeProductJointOne.getId());
            productServiceJoint.updateStoreProductJoint(storeproductJoint);
        }

        json.put("success",true);
        json.put("msg","下架成功");
        return json;
    }

    /** 项目设置 */
    @PostMapping("/productConfig")
    public JSONObject productConfig(@RequestBody StoreProductJoint storeproductJoint){
        JSONObject json = new JSONObject();
        Integer spj_id = productServiceJoint.updateStoreProductJoint(storeproductJoint);
        json.put("success",true);
        json.put("msg","设置成功");
        return json;
    }

    /** 项目设置展示 */
    @PostMapping("/showProductConfig")
    public StoreProductJoint showProductConfig(Long storeId,Long productId){
        StoreProductJoint storeProductJoint = productServiceJoint.selectStoreProductByStoreIdAndStoreId(storeId,productId);
        return storeProductJoint;
    }

    /** 项目设置展示 */
    @GetMapping("/showProductConfig/{storeProductJointId}")
    public StoreProductJoint showProductConfig2(@PathVariable Long storeProductJointId){
        StoreProductJoint storeProductJoint = productServiceJoint.selectStoreProductById(storeProductJointId);
        return storeProductJoint;
    }

    @PostMapping("/shelves/up/{productId}")
    @ApiOperation("上架")
    public JSONObject shelvesUp(@PathVariable Long productId){
        JSONObject json = new JSONObject();
        json.put("success",false);
        json.put("msg","上架失败");
        StoreUserRole role = getStoreUserRole();
        if(null == role){
            return json;
        }
        Store store = storeService.selectStoreById(role.getStoreId());
        if(!DicConstants.SYS_Y.getCode().equals(store.getVipState())){
            json.put("msg","会员已到期，请续费后再试");
            return json;
        }
        StoreProduct product = productService.selectStoreProductById(productId);
        if(DicConstants.SYS_Y.getCode().equals(product.getNewUserState())){
            Boolean flag = checkNewUserStateProduct(role.getStoreId());
            if(flag){
                json.put("msg","同时只能有一个新人专享商品");
                return json;
            }
        }
        product.setUpdateBy(getLoginStoreUserId());
        product.setUpdateType(DicConstants.BUSINESS_Business.getCode());
        product.setState(DicConstants.SYS_Y.getCode());
        StoreProductBack back = backService.selectStoreProductBackById(product.getProductBackId());
        back.setState(DicConstants.SYS_Y.getCode());
        back.setUpdateBy(getLoginStoreUserId());
        back.setUpdateType(DicConstants.BUSINESS_Business.getCode());
        backService.updateStoreProductBack(back);
        productService.updateStoreProduct(product);
        json.put("success",true);
        json.put("msg","上架成功");

        updateSecondClassify(store);
        return json;
    }

    private Boolean checkNewUserStateProduct(Long storeId){
        StoreProduct product = new StoreProduct();
        product.setStoreId(storeId);
        product.setState(DicConstants.SYS_Y.getCode());
        product.setNewUserState(DicConstants.SYS_Y.getCode());

        return productService.selectStoreProductList(product).size()>0?true:false;
    }
    @PostMapping("/shelves/down/{productId}")
    @ApiOperation("下架")
    public JSONObject shelvesDown(@PathVariable Long productId){
        JSONObject json = new JSONObject();
        json.put("success",false);
        json.put("msg","下架失败");
        StoreUserRole role = getStoreUserRole();
        if(null == role){
            return json;
        }
        StoreProduct product = productService.selectStoreProductById(productId);
        product.setUpdateBy(getLoginStoreUserId());
        product.setUpdateType(DicConstants.BUSINESS_Business.getCode());
        product.setState(DicConstants.SYS_N.getCode());
        product.setOffTime(new Date());
        StoreProductBack back = backService.selectStoreProductBackById(product.getProductBackId());
        back.setState(DicConstants.SYS_N.getCode());
        back.setUpdateBy(getLoginStoreUserId());
        back.setUpdateType(DicConstants.BUSINESS_Business.getCode());
        backService.updateStoreProductBack(back);
        productService.updateStoreProduct(product);
        updateSecondClassify(storeService.selectStoreById(role.getStoreId()));
        json.put("success",true);
        json.put("msg","下架成功");
        return json;
    }

    /**
     * 同步团单到其它门店
     * @param storeIds
     * @return
     */
    @PostMapping("/tongbuSub")
    public AjaxResult tongbuSub(String storeIds){
        StoreUserRole role = getStoreUserRole();
        StoreProduct storeProductQuery = new StoreProduct();
        storeProductQuery.setStoreId(role.getStoreId());
        storeProductQuery.setState(DicConstants.SYS_Y.getCode());
        //所有团单
        List<StoreProduct> storeProductList= productService.selectStoreProductList(storeProductQuery);
        if(storeProductList.size()>0){
            Long storeUserId= getLoginStoreUserId();
            List<Store> list=storeService.selectStoreByUserId(storeUserId);
            //所有有权限的
            Map<Long,Store> roleStore= list.stream().collect(Collectors.toMap(Store::getId, Function.identity()));
            //选中的有权限的
            Map<Long,Store> selectStore=new HashMap<>();
            String selectStoreIds[]=storeIds.split(",");
            for (String storeIdStr: selectStoreIds) {
               Long storeid= Long.parseLong(storeIdStr);
                if(roleStore.containsKey(storeid)){
                    selectStore.put(storeid,roleStore.get(storeid));
                }else{
                    //
                    return AjaxResult.unAuthorize();
                }
            }
        AdapaySettleaccount adapaySettleaccountQuery=new AdapaySettleaccount();
        adapaySettleaccountQuery.getParams().put("storeIds",selectStoreIds);
        List<AdapaySettleaccount>  listSettleaccount= adapaySettleaccountService.selectAdapaySettleaccountList(adapaySettleaccountQuery);
        //已经实名的门店
        Map<Long,AdapaySettleaccount> mapSettleaccount=listSettleaccount.stream().collect(Collectors.toMap(AdapaySettleaccount::getStoreId,Function.identity()));
        for (String storeIdStr: selectStoreIds) {
            Long storeid= Long.parseLong(storeIdStr);
            if(!mapSettleaccount.containsKey(storeid)){
                Store store=selectStore.get(storeid);
                return AjaxResult.error("同步失败："+store.getStoreName()+"未实名");
            }
        }
            //
            for (StoreProduct storeProduct:storeProductList ) {
                StoreProduct storeProductNew=new StoreProduct();
                BeanUtils.copyBeanProp(storeProductNew,storeProduct);
                RichEditorAttachment richEditorAttachment=richEditorService.selectRichEditorAttachmentById(storeProduct.getInfoId());
                for (Long storeId:selectStore.keySet()) {
                    Store store=selectStore.get(storeId);
                    storeProductNew.setId(null);
                    storeProductNew.setStoreId(storeId);
                    storeProductNew.setStoreName(store.getStoreName());
                    storeProductNew.setAdCode(store.getAdCode());
                    storeProductNew.setAdName(store.getAdName());
                    storeProductNew.setProvinceName(store.getProvinceName());
                    storeProductNew.setProvinceCode(store.getProvinceCode());
                    storeProductNew.setCityCode(store.getCityCode());
                    storeProductNew.setCityName(store.getCityName());
                    storeProductNew.setLatitude(store.getLatitude());
                    storeProductNew.setLongitude(store.getLongitude());
                    storeProductNew.setGeoCode(store.getGeoCode());
                    richEditorAttachment.setId(null);
                    richEditorService.insertRichEditorAttachment(richEditorAttachment);
                    storeProductNew.setInfoId(richEditorAttachment.getId());
                    StoreProductBack back = new StoreProductBack(storeProductNew,richEditorAttachment.getAttValue());
                    back.setCreateBy(getLoginStoreUserId());
                    back.setCreateType(DicConstants.BUSINESS_Business.getCode());
                    backService.insertStoreProductBack(back);
                    storeProductNew.setProductBackId(back.getId());
                    productService.insertStoreProduct(storeProductNew);
                    back.setProductId(storeProductNew.getId());
                    backService.updateStoreProductBack(back);
                }
            }
        }else{
            //
            return AjaxResult.error("未找到已上架商品");
        }
        return AjaxResult.success("同步成功");
    }


}
